/**
 * @ngdoc module
 * @name CRM.controllers
 * @description
 *  CRM模块控制器
 */

angular.module('crm.controllers', [])

//CRM首页
.controller('CRMIndexCtrl', function($scope, $state, $ionicLoading, $ionicModal, User, Utils, IbPopup, CRM, CRM_REPORT_TIMETYPES) {
  $scope.CRM_REPORT_TIMETYPES = CRM_REPORT_TIMETYPES

  $scope.reload = function() {
    $scope.now = new Date()

    $ionicLoading.show()
    // 检查是否有权限访问 CRM
    return User.getAuthority().success(function(res) {
      if (res.isSuccess) {
        if (res.data.crm) {
          $scope.target = {}
          $scope.stage = {}
          $scope.todayReport = {}
          
          $ionicModal.fromTemplateUrl('templates/crm/new-modal.html', {
            scope: $scope,
            animation: 'fade-in'
          }).then(function(modal) {
            modal.hideDelay = 1;
            $scope.newModal = modal
          })

          var TIME_TODAY = 1

          CRM.getReport({ time: TIME_TODAY }).success(function(res) {
            if (res.isSuccess) {
              $scope.todayReport = res.data
            }
          })

          // 设置销售简报时间范围
          $scope.setReportTimeType = function(timeType) {
            $scope.reportTimeType = timeType;

            CRM.getReport({ time: timeType }).success(function(res) {
              if (res.isSuccess) {
                $scope.report = res.data
              }
            })
            .success(Utils.serverWarning)
          };

          $scope.setReportTimeType(CRM_REPORT_TIMETYPES[0].type);

          var year = $scope.now.getFullYear()
          var month = $scope.now.getMonth()

          // 获取目标
          // @Todo: 后端接口合并为一个
          angular.forEach([
            // 新增客户数
            {
              key: 'newClientCount',
              type: 1
            },
            // 新增商机数
            {
              key: 'newOppCount',
              type: 2
            },
            // 新增合同金额
            {
              key: 'newOppIncome',
              type: 6
            }
          ], function(conf) {
            CRM.getTarget({
              uid: User.addPrefix(User.uid),
              year: year,
              type: conf.type
            }).success(function(res) {
              if(res.isSuccess && res.data && res.data.month && res.data.month.length) {
                $scope.target[conf.key] = res.data.month[month]
              }
            })
          })

          // 获取商机详情
          CRM.getOppSurvey().success(function(res) {
            if(res.isSuccess) {
              $scope.oppSurver = res.data
              // $scope.stage.opportunity = res.data
            }
          })

        } else {
          Utils.promptNoPermission();
        }
      }
    })
    .success(Utils.serverWarning)
    .finally(function() {
      $ionicLoading.hide()
      $scope.$broadcast('scroll.refreshComplete')
    })
  }

  // 业绩目标设置提示
  $scope.showTargetSetupTip = function() {
    IbPopup.alert({
      title: '提示',
      content: '<p class="text-center" style="color:#666;">业绩目标需在PC端进行设置<br>首页&gt;业绩目标&gt;设置业绩目标</p>'
    })
  }

  $scope.reload()
})

//CRM联系人列表
.controller('CRMContactCtrl', function($scope, dateFilter, groupByFilter, orderByFilter, Utils, SearchModal, CRMContact) {
  $scope.tabs = [
    {
      text: '全部联系人',
      value: 'all'
    },
    {
      text: '我的联系人',
      value: 'my'
    },
    {
      text: '下属联系人',
      value: 'sub'
    },
    {
      text: '共享联系人',
      value: 'share'
    }
  ];

  $scope.onTab = function(tab) {
    $scope.contactList.queryParams.range = tab.value
    $scope.confirmFilters()
  }

  // 按名字、时间、公司排序
  $scope.orderType = 'letter';
  $scope.orderDesc = false;

  function addOrderFieldToList(list) {
    return list.map(function(item) {
      // 增加用于分组的字段
      item.letter = item.firstCase.charAt(0).toUpperCase();
      item.formattedDate = dateFilter(item.createtime * 1000, 'yyyy-MM-dd');
      item.company = item.company || '暂无';
      return item;
    });
  }

  // 获取联系人标签
  CRMContact.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
    }
  });

  $scope.contactList = {
    queryParams: {
      limit: 10000,
      order: {
        'name': 1
      }
    },
    load: function() {
      var that = this;
      this.loading = true;
      CRMContact.list(that.queryParams).success(function(res) {
          if (res.isSuccess) {
            that.list = addOrderFieldToList(res.data.list)
            that.total = res.data.total;
          }
        })
        .success(Utils.serverWarning)
        .finally(function() {
          that.loading = false;
          $scope.$broadcast('scroll.refreshComplete');
        });
    },
    reset: function() {
      this.list = [];
      this.total = 0;
      this.loading = false;
      this.hasMore = true;
    },
    reload: function() {
      this.reset();
      this.load();
    }
  };

  // 搜索联系人
  $scope.search = new SearchModal({
    scope: $scope,
    templateUrl: 'templates/crm/contact-search-modal.html',
    searchFunc: function(params) {
      return CRMContact.list({
        keyword: params.key
      }).success(function(res) {
        res.data.list = addOrderFieldToList(res.data.list)
      });
    }
  });

  //确定归属分类
  $scope.confirmFilters = function() {
    $scope.contactList.reload();
  };
})

.controller('CRMContactFormCtrl', function($scope, $state, $ionicHistory, $ionicScrollDelegate, $ionicModal, Utils, IbPopup, CRMContact, CRMUtils, CRM_CONTACT_EXTEND) {
  $scope.form = {
    extends: []
  };
  $scope.stateName = $state.current.name;
  $scope.isContactInfoShowed = false

  // 获取联系人标签
  CRMContact.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
      CRMUtils.initTagsToForm($scope.form, $scope.tagGroups);
    }
  });

  $scope.selectClient = function() {
    CRMUtils.openClientModal({
      cid: $scope.form.client ? $scope.form.client.cid : '',
      callback: function(client) {
        $scope.form.client = client;
      }
    });
  };

  $scope.showContactInfo = function() {
    $scope.isContactInfoShowed = true;
    $ionicScrollDelegate.resize();
  };

  // 添加联系方式
  $scope.addContactWay = function(key) {
    $scope.form.extends.push({
      key: key,
      value: ''
    })
  }

  $scope.removeContactWay = function(index) {
    $scope.form.extends.splice(index, 1)
  }


  $ionicModal.fromTemplateUrl('templates/crm/contact-way.html', {
    scope: $scope
  }).then(function(modal) {
    modal.scope.contactWays = CRM_CONTACT_EXTEND
    $scope.contactWayModal = modal
    $scope.$on('$ionicView.leave', modal.hide.bind(modal))
    $scope.$on('$destroyed', modal.remove.bind(modal))
  })

  $scope.onSubmitSuccess = function(contactid) {
    $ionicHistory.clearCache(['crm.contact'])
    IbPopup.tip($scope.stateName === 'crm.addContact' ? '新增成功' : '编辑成功', 'success')
    .then(function() {
      $scope.contactForm.$setPristine()
      $state.go('crm.contactView', { contactid: contactid }, { location: 'replace' })
    });
  };

  $scope.submit = angular.noop;

  Utils.checkFormDirtyBeforeLeave($scope, 'contactForm')
})

//CRM-添加联系人
.controller('CRMAddContactCtrl', function($scope, $ionicHistory, $stateParams, $controller, $ionicLoading, Utils, CRMContact, CRMUtils) {

  $controller('CRMContactFormCtrl', {
    $scope: $scope
  });

  if ($stateParams.client) {
    $scope.form.client = $stateParams.client;
  }

  $scope.form.gender = '0';
  $scope.form.extends = [
    { key: 'mobile', value: '' },
    { key: 'email', value: '' }
  ]
  $scope.submit = function() {
    $ionicLoading.show();
    CRMContact.create(CRMUtils.buildContactFormData($scope.form))
      .success(function(res) {
        if (res.isSuccess) {
          $scope.onSubmitSuccess(res.data.contactid);
        }
      })
      .success(CRMUtils.formValidateError)
      .finally($ionicLoading.hide);
  };
})

//CRM-编辑联系人
.controller('CRMEditContactCtrl', function($scope, $controller, $stateParams, $ionicLoading, Utils, CRMContact, CRMUtils) {
  $controller('CRMContactFormCtrl', {
    $scope: $scope
  });

  // 获取联系人信息
  $ionicLoading.show();
  CRMContact.view($stateParams)
    .success(function(res) {
      if (res.isSuccess) {
        $scope.form = res.data;
        $scope.form.birthday = res.data.birthday == '0' ? '' : new Date(res.data.birthday * 1000);
        CRMUtils.setTagsToForm($scope.form, res.data.tags);
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);

  $scope.submit = function() {
    $ionicLoading.show();

    CRMContact.update(CRMUtils.buildContactFormData($scope.form))
      .success(function(res) {
        if (res.isSuccess) {
          $scope.onSubmitSuccess($stateParams.contactid);
        }
      })
      .success(CRMUtils.formValidateError)
      .finally($ionicLoading.hide);
  }

  $scope.removeContact = function() {
    CRMUtils.confirmRemoveContact($stateParams)
  }
})

//CRM-联系人详情
.controller('CRMContactViewCtrl', function($scope, $state, $stateParams, $ionicLoading, $ionicActionSheet, $ionicHistory, Utils, CRMContact, CRMUtils) {
  $ionicLoading.show();
  CRMContact.view($stateParams).success(function(res) {
      if (res.isSuccess) {
        $scope.contact = res.data;
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);
})

//CRM客户
.controller('CRMClientCtrl', function($scope, $ionicScrollDelegate, $stateParams, $controller, SearchModal, Utils, CRMClient) {
  $scope.filterGroups = [
    {
      groupName: '创建时间',
      groupKey: 'clientList.queryParams.createtime',
      items: [
        {
          text: '不限',
          value: '0'
        },
        {
          text: '今天',
          value: '1'
        },
        {
          text: '昨天',
          value: '2'
        },
        {
          text: '本周',
          value: '3'
        },
        {
          text: '上周',
          value: '4'
        },
        {
          text: '本月',
          value: '5'
        },
        {
          text: '上月',
          value: '6'
        }
      ],
      selected: 0
    },
    {
      groupName: '跟进时间',
      groupKey: 'clientList.queryParams.lasteventtime',
      items: [
        {
          text: '不限',
          value: '0'
        },
        {
          text: '今天',
          value: '1'
        },
        {
          text: '昨天',
          value: '2'
        },
        {
          text: '本周',
          value: '3'
        },
        {
          text: '上周',
          value: '4'
        },
        {
          text: '本月',
          value: '5'
        },
        {
          text: '上月',
          value: '6'
        }
      ],
      selected: 0
    }
  ]
  $scope.selectFilterItem = function(item, filterGroup) {
    $scope.$eval(filterGroup.groupKey + '="' + item.value + '"')
    $scope.clientList.reload()
  }
  // 获取客户标签
  // @Todo: 目前标签的过滤结果是合集，需要后端修改为交集
  // CRMClient.tagList().success(function(res) {
  //   if (res.isSuccess) {
  //     angular.forEach(res.data, function(tagGroup, index) {
  //       var groupKey = 'clientList.queryParams.tags[' + tagGroup.groupid + ']'
  //       var items = tagGroup.taglist.map(function(tag) {
  //         return {
  //           text: tag.name,
  //           value: tag.tagid
  //         }
  //       })
  //       var filterGroup = {
  //         groupName: tagGroup.name,
  //         groupKey: groupKey,
  //         items: items,
  //         selected: 0
  //       }

  //       items.unshift({
  //         text: '不限',
  //         value: ''
  //       })

  //       $scope.filterGroups.splice(index, 0, filterGroup)
  //     })
  //   }
  // });

  $scope.clientList = {
    list: [],
    queryParams: {
      range: 'all',
      tags: {},
      createtime: '0',
      lasteventtime: '0'
    },
    hasMore: true,
    load: function() {
      var that = this;
      that.loading = true;
      that.queryParams.offset = that.list.length;

      CRMClient.list(that.queryParams).success(function(res) {
          if (res.isSuccess) {
            Utils.concatTo(that.list, res.data.list);
            that.total = res.data.total;
            that.hasMore = that.total > that.list.length;
            $ionicScrollDelegate.resize();
          }
        })
        .success(Utils.serverWarning)
        .finally(function() {
          that.loading = false;
          $scope.$broadcast('scroll.refreshComplete');
        });
    },
    reset: function() {
      this.list = [];
      this.total = 0;
      this.loading = false;
      this.hasMore = true;
    },
    reload: function() {
      this.reset();
      this.load();
    }
  };

  // 搜索客户
  $scope.search = new SearchModal({
    scope: $scope,
    templateUrl: 'templates/crm/client-search-modal.html',
    searchFunc: function(params) {
      return CRMClient.list({
        keyword: params.key
      });
    }
  });

  $scope.tabs = [
    {
      text: '全部客户',
      value: 'all'
    },
    {
      text: '我的客户',
      value: 'my'
    },
    {
      text: '下属客户',
      value: 'sub'
    },
    {
      text: '久未联系',
      value: 'estranged'
    },
    {
      text: '共享客户',
      value: 'share'
    }
  ]

  $scope.onTab = function(tab) {
    $scope.clientList.queryParams.range = tab.value
    $scope.confirmFilters()
  }

  //确定归属分类
  $scope.confirmFilters = function() {
    $scope.clientList.reload();
  };
})

//CRM-客户表单基础控制器
.controller('CRMClientFormCtrl', function($scope, $state, $window, $ionicLoading, $ionicHistory, mapFilter, Utils, IbPopup, CRMContact, CRMClient, CRMUtils, DefaultBack) {
  $scope.form = {};
  $scope.stateName = $state.current.name;

  $scope.$on('$ionicView.enter', function() {
    var contact = JSON.parse($window.sessionStorage.getItem('crm.addcontact'));
    if (contact) {
      $window.sessionStorage.removeItem('crm.addcontact')
      $scope.form.contacts = $scope.form.contacts || [];
      $scope.form.contacts.push(contact);
    }
  })

  function getContactIds() {
    return $scope.form.contacts && $scope.form.contacts.length ? mapFilter($scope.form.contacts, 'contactid') : [];
  }

  // 绑定联系人
  $scope.attachContact = function() {
    CRMUtils.openContactModal({
      params: {
        type: 'client'
      },
      selected: getContactIds(),
      callback: function(selected) {
        $scope.form.contacts = selected;
      }
    })
  };

  // 解绑联系人
  $scope.detachContact = function(contact) {
    Utils.eliminate($scope.form.contacts, contact);
  };

  $scope.submitAttachContact = function(cid) {
    return CRMContact.related({
      type: 'client',
      cid: cid,
      contactid: getContactIds()
    });
  };

  $scope.submitPromise = function(promise) {
    $ionicLoading.show();
    return promise.success(function(res) {
        if (res.isSuccess) {
          $ionicHistory.clearCache(['crm.client'])
          $scope.submitAttachContact(res.data.cid)
          $scope.clientForm.$setPristine()
        }
      })
      .success(CRMUtils.formValidateError)
      .success($ionicLoading.hide)
      .error($ionicLoading.hide);
  };

  // 获取客户标签
  CRMClient.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
      CRMUtils.initTagsToForm($scope.form, $scope.tagGroups);
    }
  });

  Utils.checkFormDirtyBeforeLeave($scope, 'clientForm')
})

//CRM-添加客户信息
.controller('CRMAddClientCtrl', function($scope, $state, $stateParams, $controller, $ionicScrollDelegate, IbPopup, CRMClient, $http, Settings) {
  $controller('CRMClientFormCtrl', {
    $scope: $scope
  });
  $scope.isClientInfoShowed = false;

  $scope.addMoreInfo = function() {
    $scope.isClientInfoShowed = true;
    $ionicScrollDelegate.resize();
  };
  $scope.form.likefullnames = [];
  $scope.likeFullNamesShowValue = false;
  // 检查是否有相似的公司名称
  $scope.checkLikeFullName = function (value) {
      clearTimeout(this.timer);
      this.timer = setTimeout(function () {
          $http.post(Settings.hostUrl + '?r=crm/api/getlikeclient', {'fullname':value}).success(function (ret) {
            $scope.form.likefullnames = ret.data
            $scope.likeFullNamesShow();
          });
      }, 200);
  };

  $scope.likeFullNamesNotShow = function () {
    $scope.likeFullNamesShowValue = false;
  };

  $scope.likeFullNamesShow = function () {
    if ($scope.form.likefullnames.length != 0) {
      $scope.likeFullNamesShowValue = true;
    } else {
      $scope.likeFullNamesShowValue = false;
    }
  };

  $scope.submit = function() {
    $scope.submitPromise(CRMClient.create($scope.form))
      .success(function(res) {
        if (res.isSuccess) {
          IbPopup.tip('新增成功', 'success').then(function() {
            $state.go('crm.clientView', res.data, { location: 'replace' })
          })
        }
      });
  }
})

//CRM-编辑客户信息
.controller('CRMEditClientCtrl', function($scope, $window, $controller, $ionicLoading, $stateParams, Utils, IbPopup, CRMClient, CRMUtils) {
  $controller('CRMClientFormCtrl', {
    $scope: $scope
  });
  $scope.isClientInfoShowed = true;

  $ionicLoading.show();
  CRMClient.view($stateParams)
    .success(function(res) {
      if (res.isSuccess) {
        $scope.form = res.data;
        CRMUtils.setTagsToForm($scope.form, res.data.tags);
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);

  $scope.removeClient = function() {
    CRMUtils.confirmRemoveClient($stateParams);
  }

  $scope.submit = function() {
    $scope.submitPromise(CRMClient.update($scope.form))
      .success(function(res) {
        if (res.isSuccess) {
          IbPopup.tip('编辑成功', 'success').then(function() {
            $window.history.back()
          });
        }
      });
  };
})

//CRM-客户详情页
.controller('CRMClientViewCtrl', function($scope, $state, $stateParams, $ionicLoading, $ionicActionSheet, $ionicHistory, mapFilter, Utils, CRMClient, CRMEvent, CRMOpportunity, CRMUtils) {

  $ionicLoading.show();
  CRMClient.view($stateParams)
    .success(function(res) {
      if (res.isSuccess) {
        $scope.client = res.data;
        CRMUtils.setTagsToForm($scope.client, res.data.tags);
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);

  // 获取客户标签
  CRMClient.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
    }
  });

  $scope.activeTab = 'survey';

  function loadRelatedEvent() {
    if ($scope.eventListLoaded) return;
    $ionicLoading.show();
    CRMEvent.list({
        cid: $stateParams.cid,
        limit: 10000
      })
      .success(function(res) {
        if (res.isSuccess) {
          $scope.eventList = res.data.list;
          $scope.eventListLoaded = true;
        }
      })
      .success(Utils.serverWarning)
      .finally($ionicLoading.hide);
  }

  function loadRelatedOpportunity() {
    if ($scope.oppListLoaded) return;
    $ionicLoading.show();
    CRMOpportunity.list({
        cid: $stateParams.cid,
        limit: 10000
      })
      .success(function(res) {
        if (res.isSuccess) {
          $scope.oppList = res.data.list;
          $scope.oppListLoaded = true;
        }
      })
      .success(Utils.serverWarning)
      .finally($ionicLoading.hide);
  }

  $scope.setClientTab = function(type) {
    $scope.activeTab = type || 'survey';
    if (type == 'event') {
      loadRelatedEvent();
    } else if (type == 'opportunity') {
      loadRelatedOpportunity();
    }
  };

  // 打开新建关联数据窗口
  $scope.openAttachModal = function() {
    $scope.__attachOpts = {
      params: {
        client: $scope.client
      }
    };
    CRMUtils.openAttachModal($scope);
  };

  // 关联联系人
  $scope.selectContact = function() {
    CRMUtils.selectContactToClient($stateParams.cid, $scope.client.contacts ? mapFilter($scope.client.contacts, 'contactid') : [], function(res) {
      if (res.isSuccess) {
        $ionicHistory.clearCache([$state.current.name]).then($state.reload);
      }
    });
  };

  // // 当选择标签时更新数据
  // $scope.onTagChange = function() {
  //   CRMClient.update($scope.client).success(function(res) {
  //     if (res.isSuccess) {
  //       $ionicHistory.clearCache(['crm.client']);
  //     }
  //   });
  // };
})

//CRM-商机首页
.controller('CRMOpportunityCtrl', function($scope, $ionicScrollDelegate, SearchModal, $stateParams, Utils, CRMOpportunity) {
  $scope.filterGroups = [
    {
      groupName: '商机状态',
      groupKey: 'oppList.queryParams.status',
      items: [
        {
          text: '不限',
          value: ''
        },
        {
          text: '进行中',
          value: '0'
        },
        {
          text: '已成交',
          value: '1'
        },
        {
          text: '已失败',
          value: '2'
        }
      ],
      selected: 0
    },
    {
      groupName: '创建时间',
      groupKey: 'oppList.queryParams.createtime',
      items: [
        {
          text: '不限',
          value: '0'
        },
        {
          text: '今天',
          value: '1'
        },
        {
          text: '昨天',
          value: '2'
        },
        {
          text: '本周',
          value: '3'
        },
        {
          text: '上周',
          value: '4'
        },
        {
          text: '本月',
          value: '5'
        },
        {
          text: '上月',
          value: '6'
        }
      ],
      selected: 0
    },
    {
      groupName: '更新时间',
      groupKey: 'oppList.queryParams.updatetime',
      items: [
        {
          text: '不限',
          value: '0'
        },
        {
          text: '今天',
          value: '1'
        },
        {
          text: '昨天',
          value: '2'
        },
        {
          text: '本周',
          value: '3'
        },
        {
          text: '上周',
          value: '4'
        },
        {
          text: '本月',
          value: '5'
        },
        {
          text: '上月',
          value: '6'
        }
      ],
      selected: 0
    }
  ]
  $scope.selectFilterItem = function(item, filterGroup) {
    $scope.$eval(filterGroup.groupKey + '="' + item.value + '"')
    $scope.oppList.reload()
  }

  $scope.tabs = [
  {
    text: '全部商机',
    value: 'all'
  },
  {
    text: '我的商机',
    value: 'my'
  },
  {
    text: '下属商机',
    value: 'sub'
  },
  {
    text: '共享商机',
    value: 'share'
  }
  ];

  // 搜索客户
  $scope.search = new SearchModal({
    scope: $scope,
    templateUrl: 'templates/crm/opportunity-search-modal.html',
    searchFunc: function(params) {
      return CRMOpportunity.list({
        keyword: params.key
      });
    }
  });

  $scope.oppList = {
    list: [],
    queryParams: {
      tags: {},
      range: 'all',
      createtime: '0',
      updatetime: '0',
      status: ''
    },
    hasMore: true,
    load: function() {
      var that = this;
      that.loading = true;
      that.queryParams.offset = that.list.length;

      CRMOpportunity.list(that.queryParams).success(function(res) {
          if (res.isSuccess) {
            Utils.concatTo(that.list, res.data.list);

            that.total = res.data.total;
            that.hasMore = that.total > that.list.length;
            
            if ($stateParams.status) {
              that.list = that.list.filter(function(item) {
                return item.status === $stateParams.status
              })
            }
            
            $ionicScrollDelegate.resize();
          }
        })
        .success(Utils.serverWarning)
        .finally(function() {
          that.loading = false;
          $scope.$broadcast('scroll.refreshComplete');
        });
    },
    reset: function() {
      this.list = [];
      this.total = 0;
      this.loading = false;
      this.hasMore = true;
    },
    reload: function() {
      this.reset();
      this.load();
    }
  };

  if ($stateParams.tag) {
    var tag = $stateParams.tag
    var queryParams = $scope.oppList.queryParams
    queryParams.range = 'my'
    queryParams.tags[tag.groupid] = [tag.tagid];
  }

  $scope.onTab = function(tab) {
    $scope.oppList.queryParams.range = tab.value
    $scope.confirmFilters()
  }

  //确定归属分类
  $scope.confirmFilters = function() {
    $scope.oppList.reload();
  };
})

//CRM-商机详情页
.controller('CRMOpportunityViewCtrl', function($scope, $state, $stateParams, $ionicActionSheet, $ionicLoading, $ionicHistory, mapFilter, dateFilter, Utils, CRMOpportunity, CRMEvent, CRMUtils) {
  $scope.activeTab = 'survey';

  $ionicLoading.show();
  CRMOpportunity.view($stateParams).success(function(res) {
      if (res.isSuccess) {
        $scope.opp = res.data;
        $scope.opp.cid = res.data.client && res.data.client.cid ? res.data.client.cid : '';
        $scope.opp.contactid = res.data.contacts ? mapFilter(res.data.contacts, 'contactid') : [];
        CRMUtils.setTagsToForm($scope.opp, res.data.tags);
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);

  function clearOpportunityCache(res) {
    if (res.isSuccess) $ionicHistory.clearCache(['crm.opportunity']);
  }

  // 打开新建关联数据窗口
  $scope.openAttachModal = function() {
    $scope.__attachOpts = {
      newOpp: false,
      newContact: false,
      attachContact: $scope.opp.cid ? true : false,
      params: {
        client: $scope.opp.client,
        opportunity: $scope.opp
      }
    };
    CRMUtils.openAttachModal($scope);
  };
  // 关联联系人
  $scope.selectContact = function() {
    CRMUtils.openContactModal({
      selected: $scope.opp.contactid,
      params: {
        type: 'opp',
        cid: $scope.opp.cid || ''
      },
      callback: function(selected) {
        $ionicLoading.show();
        $scope.opp.contacts = selected;
        $scope.opp.contactid = mapFilter(selected, 'contactid');
        CRMOpportunity.update($scope.opp).finally($ionicLoading.hide);
      }
    });
  };

  function loadRelatedEvent() {
    if ($scope.eventListLoaded) return;
    $ionicLoading.show();
    CRMEvent.list({
        oid: $stateParams.oid,
        limit: 10000
      })
      .success(function(res) {
        if (res.isSuccess) {
          $scope.eventList = res.data.list;
          $scope.eventListLoaded = true;
        }
      })
      .success(Utils.serverWarning)
      .finally($ionicLoading.hide);
  }

  $scope.setActiveTab = function(tag) {
    $scope.activeTab = tag;
    if (tag === 'event') loadRelatedEvent();
  };

  // 获取商机标签
  CRMOpportunity.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
    }
  });
})

//CRM-商机表单
.controller('CRMOpportunityFormCtrl', function($scope, $state, $ionicLoading, $ionicHistory, mapFilter, Utils, IbPopup, CRMOpportunity, CRMUtils, DefaultBack) {
  $scope.form = {
    dealchance: 0,
    createtime: new Date()
  };

  $scope.isOppFormMoreShowed = false
  $scope.showOppFormMore = function() {
    $scope.isOppFormMoreShowed = true
  }

  $scope.stateName = $state.current.name;

  // 关联联系人
  $scope.attachContact = function() {
    CRMUtils.openContactModal({
      params: {
        type: 'opp',
        cid: $scope.form.cid
      },
      selected: $scope.form.contactid || [],
      client: $scope.client,
      callback: function(contacts) {
        $scope.contacts = contacts;
        $scope.form.contactid = mapFilter(contacts, 'contactid');
      }
    });
  };

  $scope.detachContact = function(contact) {
    Utils.toggle($scope.contacts, contact)
    $scope.form.contactid = mapFilter($scope.contacts, 'contactid');
  }

  // 关联客户
  $scope.attachClient = function() {
    CRMUtils.openClientModal({
      cid: $scope.form.cid || '',
      callback: function(client) {
        $scope.client = client;
        $scope.form.cid = client.cid;
        $scope.contacts = [];
        $scope.form.contactid = [];
      }
    });
  };

  $scope.submitPromise = function(promise) {
    $ionicLoading.show();
    return promise.success(function(res) {
        if (res.isSuccess) {
          $ionicHistory.clearCache(['crm.opportunity'])
          $scope.oppForm.$setPristine()
        }
      })
      .success(CRMUtils.formValidateError)
      .success($ionicLoading.hide)
      .error($ionicLoading.hide);
  };

  // 获取商机标签
  CRMOpportunity.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
      CRMUtils.initTagsToForm($scope.form, $scope.tagGroups);
    }
  });

  Utils.checkFormDirtyBeforeLeave($scope, 'oppForm')
})

//CRM-添加商机页
.controller('CRMAddOpportunityCtrl', function($scope, $state, $stateParams, $controller, IbPopup, CRMOpportunity, CRMUtils) {
  $controller('CRMOpportunityFormCtrl', {
    $scope: $scope
  });
  if ($stateParams.client) {
    $scope.client = $stateParams.client;
    $scope.form.cid = $stateParams.client.cid;
  }
  $scope.submit = function() {
    $scope.submitPromise(CRMOpportunity.create(CRMUtils.buildOpportunityFormData($scope.form)))
    .success(function(res) {
      if(res.isSuccess) {
        IbPopup.tip('新增成功', 'success')
        .then(function() {
          $state.go('crm.opportunityView', res.data, { location: 'replace' })
        })
      }
    })
  };
})

//CRM-编辑商机页
.controller('CRMEditOpportunityCtrl', function($scope, $window, $controller, $stateParams, $ionicLoading, Utils, mapFilter, currencyToNumberFilter, IbPopup, CRMOpportunity, CRMUtils) {
  $controller('CRMOpportunityFormCtrl', {
    $scope: $scope
  });

  $ionicLoading.show();
  CRMOpportunity.view($stateParams).success(function(res) {
      if (res.isSuccess) {
        $scope.form = res.data;
        $scope.form.createtime = new Date(res.data.createtime * 1000);
        $scope.form.expectendtime = res.data.expectendtime && res.data.expectendtime != 0 ? new Date(res.data.expectendtime * 1000) : '';
        // 格式化预计收入为数字
        $scope.form.expectincome = $scope.form.expectincome ? currencyToNumberFilter($scope.form.expectincome) : ''
        $scope.form.dealchance = +res.data.dealchance;
        $scope.form.cid = res.data.client && res.data.client.cid ? res.data.client.cid : '';
        $scope.form.contactid = res.data.contacts ? mapFilter(res.data.contacts, 'contactid') : [];
        $scope.contacts = res.data.contacts;
        $scope.client = res.data.client;
        CRMUtils.setTagsToForm($scope.form, res.data.tags);
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);

  $scope.submit = function() {
    $scope.submitPromise(CRMOpportunity.update(CRMUtils.buildOpportunityFormData($scope.form)))
    .success(function(res) {
      if(res.isSuccess) {
        IbPopup.tip('编辑成功', 'success')
        .then(function() {
          $window.history.back()
        });
      }
    })
  };

  $scope.removeOpp = function() {
    CRMUtils.confirmRemoveOpportunity($stateParams);
  }
})

// 事件首页
.controller('CRMEventCtrl', function($scope, $ionicScrollDelegate, SearchModal, Utils, CRMEvent) {
  $scope.filterGroups = [
    {
      groupName: '来源',
      groupKey: 'eventList.queryParams.source',
      items: [
        {
          text: '不限',
          value: ''
        },
        {
          text: '客户',
          value: 'client'
        },
        {
          text: '机会',
          value: 'opportunity'
        },
        {
          text: '合同',
          value: 'contract'
        }
      ],
      selected: 0
    },
    {
      groupName: '跟进时间',
      groupKey: 'eventList.queryParams.eventtime',
      items: [
        {
          text: '不限',
          value: '0'
        },
        {
          text: '今天',
          value: '1'
        },
        {
          text: '昨天',
          value: '2'
        },
        {
          text: '本周',
          value: '3'
        },
        {
          text: '上周',
          value: '4'
        },
        {
          text: '本月',
          value: '5'
        },
        {
          text: '上月',
          value: '6'
        }
      ],
      selected: 0
    }
  ]
  $scope.selectFilterItem = function(item, filterGroup) {
    $scope.$eval(filterGroup.groupKey + '="' + item.value + '"')
    $scope.eventList.reload()
  }

  $scope.tabs = [{
    text: '全部跟进',
    value: 'all'
  }, {
    text: '我的跟进',
    value: 'my'
  }, {
    text: '下属跟进',
    value: 'sub'
  }];

  $scope.onTab = function(tab) {
    $scope.eventList.queryParams.range = tab.value
    $scope.confirmFilters()
  }

  $scope.eventList = {
    list: [],
    queryParams: {},
    hasMore: true,
    load: function() {
      var that = this;
      that.loading = true;
      that.queryParams.offset = that.list.length;
      CRMEvent.list(that.queryParams).success(function(res) {
          if (res.isSuccess) {
            Utils.concatTo(that.list, res.data.list);
            that.total = res.data.total;
            that.hasMore = that.total > that.list.length;
            $ionicScrollDelegate.resize();
          }
        })
        .success(Utils.serverWarning)
        .finally(function() {
          that.loading = false;
          $scope.$broadcast('scroll.refreshComplete');
        });
    },
    reset: function() {
      this.list = [];
      this.total = 0;
      this.loading = false;
      this.hasMore = true;
    },
    reload: function() {
      this.reset();
      this.load();
    }
  };

  // 搜索客户
  $scope.search = new SearchModal({
    scope: $scope,
    templateUrl: 'templates/crm/event-search-modal.html',
    searchFunc: function(params) {
      return CRMEvent.list({
        keyword: params.key
      });
    }
  });

  //确定归属分类
  $scope.confirmFilters = function() {
    $scope.eventList.reload();
  };

  // 获取事件标签
  CRMEvent.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
    }
  });
})

// 事件表单
.controller('CRMEventFormCtrl', function($scope, $state, $ionicLoading, $ionicHistory, mapFilter, IbPopup, Utils, CRMEvent, CRMUtils, DefaultBack) {
  $scope.form = {};

  $scope.stateName = $state.current.name;

  // 关联客户
  $scope.selectClient = function() {
    CRMUtils.openClientModal({
      cid: $scope.form.client ? $scope.form.client.cid : '',
      // 清空
      callback: function(client) {
        if (client !== $scope.form.client) {
          $scope.form.client = client;
          $scope.form.cid = client.cid;
          $scope.form.opportunity = null;
          $scope.form.oid = '';
          $scope.form.contacts = [];
          $scope.form.contactid = [];
        }
      }
    });
  };

  // 关联商机
  $scope.selectOpportunity = function() {
    CRMUtils.openOpportunityModal({
      selected: $scope.form.oid || '',
      params: {
        cid: $scope.form.cid || ''
      },
      callback: function(selected) {
        if (selected !== $scope.form.opportunity) {
          $scope.form.opportunity = selected;
          $scope.form.oid = selected.oid;
          $scope.form.contacts = [];
          $scope.form.contactid = [];
        }
      }
    });
  };

  // 关联联系人
  $scope.attachContact = function() {
    CRMUtils.openContactModal({
      selected: $scope.form.contactid,
      params: {
        type: 'event',
        cid: $scope.form.cid || '',
        oid: $scope.form.oid || ''
      },
      callback: function(selected) {
        $scope.form.contacts = selected;
        $scope.form.contactid = mapFilter(selected, 'contactid');
      }
    });
  };

  $scope.detachContact = function(contact) {
    Utils.eliminate($scope.form.contacts, contact);
    $scope.form.contactid = mapFilter($scope.form.contacts, 'contactid');
  }

  // 作为 promise 的包装函数
  $scope.submitPromise = function(promise) {
    $ionicLoading.show();
    return promise.success(function(res) {
        if (res.isSuccess) {
          $ionicHistory.clearCache(['crm.event'])
          $scope.eventForm.$setPristine()
        }
      })
      .success(CRMUtils.formValidateError)
      .success($ionicLoading.hide)
      .error($ionicLoading.hide)
  };

  // 获取事件标签
  CRMEvent.tagList().success(function(res) {
    if (res.isSuccess) {
      $scope.tagGroups = res.data;
      CRMUtils.initTagsToForm($scope.form, $scope.tagGroups);
    }
  });

  Utils.checkFormDirtyBeforeLeave($scope, 'eventForm')
})

// 添加事件页
.controller('CRMAddEventCtrl', function($scope, $state, $stateParams, $controller, IbPopup, CRMEvent) {
  $controller('CRMEventFormCtrl', {
    $scope: $scope
  });

  // 如果从客户或商机中新建事件，则从 $stateParams 中传递这些数据过来
  if ($stateParams.client) {
    $scope.form.client = $stateParams.client;
    $scope.form.cid = $stateParams.client.cid;
  }
  if ($stateParams.opportunity) {
    $scope.form.opportunity = $stateParams.opportunity;
    $scope.form.oid = $stateParams.opportunity.oid;
  }

  $scope.submit = function() {
    $scope.submitPromise(CRMEvent.create($scope.form))
    .success(function(res) {
      if(res.isSuccess) {
        IbPopup.tip('新增成功', 'success')
        .then(function(){
          $state.go('crm.eventView', res.data, { location: 'replace' })
        });
      }
    })
  };
})

// 编辑事件页
.controller('CRMEditEventCtrl', function($scope, $window, $controller, $stateParams, $ionicLoading, mapFilter, Utils, IbPopup, CRMEvent, CRMUtils) {
  $controller('CRMEventFormCtrl', {
    $scope: $scope
  });

  $ionicLoading.show();
  CRMEvent.view($stateParams).success(function(res) {
      if (res.isSuccess) {
        $scope.form = res.data;
        $scope.form.cid = res.data.client ? res.data.client.cid : '';
        $scope.form.oid = res.data.opportunity ? res.data.opportunity.oid : '';
        $scope.form.contactid = res.data.contacts ? mapFilter(res.data.contacts, 'contactid') : [];
        CRMUtils.setTagsToForm($scope.form, res.data.tags);
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);

  $scope.submit = function() {
    $scope.form.aid = [];
    $scope.submitPromise(CRMEvent.update($scope.form))
    .success(function(res) {
      if(res.isSuccess) {
        IbPopup.tip('编辑成功', 'success')
        .then(function(){
          $window.history.back()
        });
      }
    })
  };

  $scope.removeEvent = function() {
    CRMUtils.confirmRemoveEvent($stateParams);
  }
})

// 事件详情页
.controller('CRMEventViewCtrl', function($scope, $state, $stateParams, $ionicLoading, $ionicActionSheet, Utils, CRMEvent, CRMUtils) {
  $ionicLoading.show();
  CRMEvent.view($stateParams).success(function(res) {
      if (res.isSuccess) {
        $scope.ev = res.data;
      }
    })
    .success(Utils.serverWarning)
    .finally($ionicLoading.hide);
})